﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SmsLib
{
    public class ShortMessage : IDisposable
    {
        private int port;
        private uint baudRate;

        public ShortMessage(int port, uint baudRate)
        {
            this.port = port;
            this.baudRate = baudRate;
        }

        public bool Start()
        {
            return SMSMessage.SMSStartService(port, baudRate, 2, 8, 0, 0, "card") != 0;
        }

        public bool Stop()
        {
            return SMSMessage.SMSStopSerice() == 1;
        }

        public bool Send(string phoneNumber, string message)
        {
            var index = SMSMessage.SMSSendMessage(Encoding.Default.GetBytes(message), Encoding.Default.GetBytes(phoneNumber));
            var result = SMSMessage.SMSQuery(index);
            return result == 1;
        }

        public ReceiveMessage Receive()
        {
            SMSMessageStruct smsStruct;
            SMSMessage.SMSGetNextMessage(out smsStruct);
            ReceiveMessage rm = null;
            string phoneNo = Encoding.Default.GetString(smsStruct.PhoneNo).Replace("\0", "");
            if (string.IsNullOrEmpty(phoneNo))
                return rm;
            rm = new ReceiveMessage();
            rm.PhoneNumber = phoneNo;
            rm.Message = Encoding.Default.GetString(smsStruct.Msg).Replace("\0", "");
            rm.ReceiveTime = Encoding.Default.GetString(smsStruct.ReceTime).Replace("\0", "");
            return rm;
        }

        public void Dispose()
        {
            Stop();
        }
    }

    public class ReceiveMessage
    {
        public string PhoneNumber { get; set; }
        public string Message { get; set; }
        public string ReceiveTime { get; set; }
    }
}
